import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Hello from '@/views/hello'
import Contact from '@/views/contact'
import Login from '@/views/login'
import Reg from '@/views/register'
import store from '@/store'
import Web from '@/views/web'

Vue.use(Router)

const router = new Router({
  //mode: 'history',
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld //主页
    },
    {
      path: '/hello',
      name: 'hello123',
      component: Hello,
      meta:{
        requiresAuth: true
      }
    },
    {
      path: '/contact',
      name: 'contact',
      component: Contact
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/reg',
      name: 'reg',
      component: Reg
    },
    {
      path:'/web',
      name:'web',
      component: Web, //此组件下存在自自路由， 模板中需要建立自己的路由视图 route-view
      children: [  //子路由
        {
          path:"",
          component: () => import('@/views/web/home')
        },
        {
          path: 'home',
          name: 'home',
          component: () => import('@/views/web/home')
        },
        {
          path: 'introduce',
          name: 'introduce',
          component: () => import('@/views/web/introduce')
        },
        {
          path: 'employment',
          name: 'employment',
          component: () => import('@/views/web/employment')
        },
        {
          path: 'consult',
          name: 'consult',
          component: () => import('@/views/web/consult')
        }
      ]

    }
  ]
})

//注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
  //获取store里面的token
  let token = store.state.token;
  //判断要去的路由有没有requiresAuth，为true 表示需要验证
  if (to.meta.requiresAuth) { //meta 是配置在路由中的 {path: '/actile',name: 'Actile',component: Actile,meta: { requiresAuth: true},
   if (token) {
    next();
   } else {
    next({
     path: '/login',
     query: { redirect: to.fullPath } // 将刚刚要去的路由path作为参数，方便登录成功后直接跳转到该路由
    });
   }
  } else {
   next(); 
  }
 });


export default router;
